package net.arogarth.aws.android.manager.views;

import java.util.ArrayList;
import java.util.List;

import net.arogarth.aws.android.lib.AmazonEc2;
import net.arogarth.aws.android.manager.DatabaseAdapter;
import net.arogarth.aws.android.manager.R;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class RegisterAsAmi extends Activity implements OnClickListener {
	private class KernerlSpinnerAdapter extends BaseAdapter {
		private Context context;
		private List<String> kernels = new ArrayList<String>();
		
		public KernerlSpinnerAdapter(Context view, Spinner spinner) {
			spinner.setAdapter(this);
			context = view;
			
			DatabaseAdapter dba = new DatabaseAdapter(context);
			
			kernels = dba.open().listKernelIds();
			
			dba.close();
		}
		
		public int getCount() {
			return kernels.size();
		}

		public String getItem(int position) {
			return kernels.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			TextView tv = new TextView(this.context);
			tv.setText(this.getItem(position));
					
			return tv;
		}
		
	}
	
	private String selectedSnapshotId;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.register_as_ami);
		
		
		((Button) findViewById(R.id.btnSave)).setOnClickListener(this);
		
		Spinner sp = ((Spinner) findViewById(R.id.spKernelId));
		new KernerlSpinnerAdapter(RegisterAsAmi.this, sp);
		
		this.selectedSnapshotId = getIntent().getExtras().getString("snapshotId");
	}

	public void onClick(View v) {
		CharSequence name = ((EditText) findViewById(R.id.etName)).getText();
		CharSequence description = ((EditText) findViewById(R.id.etDescription)).getText();
		String architectire = ((Spinner) findViewById(R.id.spArchitecture)).getSelectedItem().toString();
		
		AmazonEc2 aec2 = new AmazonEc2();
		
		aec2.params.put("Description", description.toString());
		aec2.params.put("Architecture", architectire);
		
		aec2.registerImage(this.selectedSnapshotId, name.toString());
		
		finish();
	}
}
